package com.zzs.elm.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

	private static final String URL="jdbc:mysql:///elm_servlet?characterEncoding=utf-8&allowPublicKeyRetrieval=true";
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private static final String USERNAME="root";
	private static final String PASSWORD="012345";
	
	public static Connection getConnection() throws ClassNotFoundException {
		Connection con = null;
		try {
			Class.forName(DRIVER);
			con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
	
	public static void beginTransaction(Connection con) throws Exception {
		if (con == null) {
			throw new RuntimeException();
		}
		con.setAutoCommit(false);
	}
	
	public static void commitTransaction(Connection con) throws Exception {
		if (con == null) {
			throw new RuntimeException();
		}
		con.commit();
		if (con != null) {
			con.close();
		}
	}
	
	public static void rollbackTransaction(Connection con) throws Exception {
		if (con == null) {
			throw new RuntimeException();
		}
		con.rollback();
		if (con != null) {
			con.close();
		}
	}

	public static void close(ResultSet rs, PreparedStatement pst, Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void close(ResultSet rs, PreparedStatement pst) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
